<template>
	<view class="view-contain">
		<!-- 公共组件-每个页面必须引入 -->
		<public-module :title="title" />
		<view class="tab-group">
			<view class="tab-item" :class="{ active: currentTab === index }" v-for="(item, index) in tabs" :key="index"
				@tap="handleTabClick(index)">
				{{ item }}
			</view>
		</view>
		<mescroll-uni :height="`${height}px`" :down="downOption" :up="upOption" @init="mescrollInit"
			@down="downCallback" @up="upCallback">
			<view v-if="type===2" class="search">
				<u-row gutter="12">
					<u-col span="2">
						<u-input v-model="teacherName" placeholder="姓名" border="bottom" />
					</u-col>
					<u-col v-for="(subject, index) in subjects" :key="index" span="2">
						<view class="tag" @click="selectSubject(subject)">
							{{ subject }}
						</view>
					</u-col>
				</u-row>
			</view>
			<view class="review-item" v-for="(item, index) in markList" :key="index">
				<view class="li_top_info u-flex u-flex-items-center ">
					<view class="sjmc sjmc_rank">
						<view class="rank_level">
							{{index + 1}}
						</view>
					</view>
					<view v-if="type===0|| type === 5" class="sjmc rank_name">{{ item.userName }}</view>
					<view v-if="type===1" class="sjmc rank_name">{{ item.loginName }}</view>
					<view v-if="type===2" class="sjmc rank_name">{{ item.teacherName}}</view>
					<view v-if="type === 3 || type === 4|| type === 6" class="sjmc rank_name">{{ item.title }}</view>
					<view v-if="type===0" class="kssj">{{ item.studyMarkDate }}</view>
					<view v-if="type===1" class="kssj">{{ item.kssj }}</view>
					<view v-if="type===5" class="kssj">{{ item.messageTime }}</view>

				</view>
				<view v-if="type===0" class="studyContent kssj">{{ item.studyContent }}</view>
				<view v-if="type===5" class="studyContent kssj">{{ item.messageContent }}</view>
				<view v-if="type===1" class="studyContent">
					<view class="u-flex">
						<view class="kssj">试卷名称：</view>
						<view class="sjmc">{{ item.sjmc }}</view>
					</view>
					<view class="u-flex">
						<view class="kssj">考试分数：</view>
						<view class="sjmc">{{ item.ksfs }}</view>
					</view>
				</view>


				<view v-if="type===2" class="studyContent">
					<view class="u-flex">
						<view class="kssj">教学科目：</view>
						<view class="sjmc">{{ item.subject }}</view>
						<view class="comment-btn" @click="listComment(item.teacherId, item.subject)">评价详情</view>
					</view>
					<view class="u-flex">
						<view class="kssj">大众评分：</view>
						<view class="sjmc">{{ item.evaluationScore }}</view>
						<view class="comment-btn1">纯属凑字</view>
					</view>
					<view class="u-flex">
						<view class="kssj">评价次数：</view>
						<view class="sjmc">{{ item.evaluationNumber }}</view>
						<view class="comment-btn" @click="addComment(item.teacherId, item.subject)">我要点评</view>
					</view>
				</view>
				<view v-if="type === 3 || type === 4|| type === 6" class="studyContent">
					<view class="u-flex">
						<view class="kssj">收录时间：</view>
						<view class="sjmc">{{ $u.timeFormat(item.updateTime, 'yyyy-mm-dd') }}</view>
					</view>
					<view class="u-flex">
						<view class="kssj">阅读人次：</view>
						<view class="sjmc">{{ item.views }}</view>
					</view>
					<view v-if="type === 3 || type === 4" class="u-flex">
						<view class="kssj">附件下载：</view>
						<view class="sjmc">
							<view @click="downloadAttachment(item.attachment)"
								style="color: #409EFF; text-decoration: underline; cursor: pointer;">
								{{ item.attachmentName }}
							</view>
						</view>
					</view>
					<view v-if="shareFilePath" class="share-btn" @click="shareFile">
						<u-button>分享下载的文件</u-button>
					</view>
					<view class="btn-detail u-flex-xy-center " @click="toDetail(item.content,item)">查看详情
					</view>
				</view>
			</view>
		</mescroll-uni>
		<view class="btn-add u-flex-xy-center" @click="handleAdd" v-if="currentTab !== 3 && currentTab !== 6">
			<u-icon name="plus" size="52rpx" color="#409EFF" />
		</view>
	</view>
</template>

<script>
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
	import {
		articleSlider,
		indexMarkList,
		indexWeeklist,
		teacherList,
		evaluationCheck,
		articleList,
		articleDetail,
		updateIntegral,
		messageBoardList,
		addMessageBoard
	} from "@/config/api.js";
	import {
		mapState,
		mapMutations
	} from 'vuex';

	export default {
		mixins: [MescrollMixin], // 使用mixin
		data() {
			return {
				title: '榜上有名',
				height: 0,
				type: 0,
				teacherName: '',
				subject: '',
				swipers: [],
				markList: [],
				total: 0,
				downOption: {
					use: false
				},
				upOption: {
					textNoMore: '一不小心被你看完啦~',
					toTop: {
						right: '24rpx',
						bottom: '60rpx'
					}
				},
				tabs: ['每日打卡', '行测模考', '大神经验', '老师评分', '苏榜原创',  '留言板', '公告栏'],
				currentTab: 0,
				idleTimer: null,
				idleTimeLimit: 30 * 60 * 1000, // 5分钟，单位毫秒
				shareFilePath: '', // 新增属性用于存储分享的文件路径
				subjects: ['言语', '判断', '资料', '申论', '面试'], // 新增科目标签
			};
		},
		// 监听
		watch: {
			teacherName(val, oldVal) {
				if (val !== oldVal) {
					uni.$u.debounce(this.mescroll.resetUpScroll(), 1000)
				}
			},
			subject(val, oldVal) {
				if (val !== oldVal) {
					uni.$u.debounce(this.mescroll.resetUpScroll(), 1000)
				}
			}
		},
		computed: {
			...mapState(['user'])
		},
		onShow() {
			const res = uni.getSystemInfoSync();
			this.height = res.windowHeight;
			this.mescroll.resetUpScroll();
			this.getArticleSlider();
			this.resetIdleTimer();
		},
		onShareAppMessage() {
			return {
				title: '苏榜带你上上分！',
				imageUrl: "../../static/img/share.jpg",
				path: '/pages/index/index'
			};
		},
		methods: {
			...mapMutations(['setLoginShow', 'emptyUserInfo']),
			async getArticleSlider() {
				const res = await articleSlider();
				if (res && res.rows) {
					this.swipers = res.rows.map(item => ({
						...item,
						title: item.title,
						image: item.cover
					}));
				}
			},
			onType(type) {
				this.type = type;
				this.mescroll.resetUpScroll();
			},
			/*上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10 */
			async upCallback(page) {
				try {
					let res;
					if (this.type === 0) {
						res = await indexMarkList(`?pageNum=${page.num}&pageSize=${page.size}`);
					} else if (this.type === 1) {
						res = await indexWeeklist(`?pageNum=${page.num}&pageSize=${page.size}`);
					} else if (this.type === 2) {
						res = await teacherList(
							`?pageNum=${page.num}&pageSize=${page.size}&teacherName=${this.teacherName}&subject=${this.subject}`
						);
					} else if (this.type === 3) { // 大神经验
						res = await articleList(`?channelId=0&pageNum=${page.num}&pageSize=${page.size}`);
					} else if (this.type === 4) { // 苏榜原创
						res = await articleList(`?channelId=5&pageNum=${page.num}&pageSize=${page.size}`);
					} else if (this.type === 5) {
						res = await messageBoardList(`?pageNum=${page.num}&pageSize=${page.size}`);
					} else if (this.type === 6) { // 公告栏
						res = await articleList(`?channelId=2&pageNum=${page.num}&pageSize=${page.size}`);
					}
					if (res && res.rows) {
						this.total = res.total;
						// 后台接口有返回列表的总数据量
						this.mescroll.endBySize(res.rows?.length || 0, res.total);
						// 如果是第一页需手动制空列表
						if (page.num == 1) {
							this.markList = [];
						}
						this.markList = Object.freeze(this.markList.concat(res.rows));
					}
				} catch (error) {
					//联网失败, 结束加载
					this.mescroll.endErr();
				}
			},
			handleAdd() {
				switch (this.currentTab) {
					case 0: // 新增每日打卡
						this.addStudy()
						break
					case 1: // 新增行测模考
						this.addReview()
						break
					case 2: // 新增大神经验
						uni.navigateTo({
							url: '/pages/experience/components/add'
						})
						break
					case 3: // 新增老师评分
						this.addComment()
						break
					case 5: // 新增留言
						this.addMessageBoard()
						break
				}
			},
			async toDetail(content, item) {
				try {
					const res = await articleDetail(item.id);
					const data = JSON.stringify(res.data);
					if (res.code === 200) {
						// 如果文章详情获取成功，则导航到详情页面  
						uni.navigateTo({
							url: `/pages/experience/components/detail?content=${encodeURIComponent(content)}`
						});
					} else {
						uni.$u.toast(res.msg);
					}

				} catch (error) {
					this.mescroll.endErr();
					console.error('获取文章详情失败:', error);
				}
			},
			addStudy() {
				uni.navigateTo({
					url: `/pages/study/components/add`
				});
			},
			addReview() {
				uni.navigateTo({
					url: `/pages/review/components/add`
				});
			},
			addMessageBoard() {
				uni.navigateTo({
					url: `/pages/messageBoard/components/add`
				});
			},
			async addComment(teacherId, subject) {
				try {
					const res = await evaluationCheck({
						teacherId: teacherId,
						subject: subject
					});
					const data = JSON.stringify(res.data);
					if (res.code === 200) {
						if (res.data.length !== 0) {
							console.log(data);
							uni.navigateTo({
								url: `/pages/teachercomment/components/add?data=${data}&type=3`
							});
						} else {
							console.log(teacherId + subject);
							uni.navigateTo({
								url: `/pages/teachercomment/components/add?teacherId=${teacherId}&subject=${subject}&type=1`
							});
						}
					} else {
						uni.$u.toast(res.msg);
					}

				} catch (error) {
					uni.$u.toast('请求异常，请检查网络或联系管理员');
					console.error('evaluationCheck 请求失败:', error);
				}
			},
			async listComment(teacherId, subject) {
				uni.navigateTo({
					url: `/pages/teachercomment/index?teacherId=${teacherId}&subject=${subject}`
				});
			},
			handleTabClick(index) {
				this.currentTab = index
				switch (index) {
					case 0: // 每日打卡榜
						this.onType(0)
						break
					case 1: // 行测模考榜
						this.onType(1)
						break
					case 2: // 大神经验榜
						this.onType(3)
						break
					case 3: // 讲师测评榜
						this.onType(2)
						break
					case 4: // 苏榜原创
						this.onType(4)
						break
					case 5: // 留言板
						this.onType(5)
						break
					case 6: // 通知
						this.onType(6)
						break
				}
			},
			resetIdleTimer() {
				if (this.idleTimer) {
					clearTimeout(this.idleTimer);
				}
				this.idleTimer = setTimeout(() => {
					console.log('用户30分钟没操作');
					this.emptyUserInfo()
				}, this.idleTimeLimit);
			},
			async downloadAttachment(url) {
				if (!this.user.userId) {
					uni.$u.toast('请先登录');
					return;
				}
				if (this.user.totalIntegral < 10) {
					uni.$u.toast('积分不足，无法下载');
					return;
				}

				try {
					// 从 URL 中提取文件名和后缀
					const fileName = url.substring(url.lastIndexOf('/') + 1);
					const fileExtension = fileName.substring(fileName.lastIndexOf('.'));

					// 显示下载loading
					uni.showLoading({
						title: '下载中...',
						mask: true
					});

					console.log('开始下载文件，URL:', url);

					const sendFileToChat = (savedFilePath) => {
						this.shareFilePath = savedFilePath;
						uni.$u.toast('文件下载成功，可以分享！');
					};

					// 微信小程序专用下载方式
					const downloadResult = await uni.downloadFile({
						url: url,
						header: {
							'Content-Type': 'application/pdf' // 根据文件类型设置
						}
					});

					console.log('下载结果:', downloadResult); // 添加日志输出

					// 检查下载结果
					if (downloadResult[1].statusCode === 200) {
						const tempFilePath = downloadResult[1].tempFilePath;
						// 积分扣除
						await this.updateIntegral({
							action: 'downloadArticle'
						});
						// 保存到本地文件系统
						const savedFilePath = await new Promise((resolve, reject) => {
							wx.getFileSystemManager().saveFile({
								tempFilePath: tempFilePath,
								filePath: wx.env.USER_DATA_PATH + '/' + fileName, // 使用提取的文件名
								success: function(res) {
									const savedFilePath = res.savedFilePath;
									resolve(savedFilePath); // 确保返回保存的文件路径
									sendFileToChat(savedFilePath); // 在这里调用
								},
								fail: function(err) {
									console.log('保存文件失败：', err);
									reject(err); // 处理失败情况
								}
							});
						});
					} else {
						throw new Error('下载失败，未获取到文件路径');
					}

				} catch (error) {
					uni.$u.toast('下载失败，请稍后重试');
					console.error('文件下载失败:', error);
				} finally {
					uni.hideLoading();
				}
			},
			shareFile() {
				if (this.shareFilePath) {
					wx.shareFileMessage({
						filePath: this.shareFilePath,
						success: function() {
							console.log('文件已成功分享');
						},
						fail: function(err) {
							console.log('分享文件失败：', err);
						}
					});
				} else {
					uni.$u.toast('没有文件可以分享');
				}
			},
			async updateIntegral(request) { // 新增方法
				try {
					const res = await updateIntegral(request);
					if (res.code === 200) {
						console.log('积分更新成功');
					} else {
						uni.$u.toast(res.data.msg);
					}
				} catch (error) {
					console.error('更新积分失败:', error);
				}
			},
			selectSubject(subject) {
				this.subject = subject; // 设置选中的科目
				this.mescroll.resetUpScroll(); // 重置上拉加载
			},
		},
	};
</script>

<style lang="scss" scoped>
	page {
		background-image: radial-gradient(60vw 60vw at 70% 30%, #D9F9F3, #f7f7f7, #F7F7F7);
		background-color: #F5F6F5;
		padding-top: 0;
		padding-bottom: 0px;
	}

	.view-contain {
		position: relative;

		.banner {
			margin: 24rpx 24rpx;
		}

		.info {
			margin: 40rpx 20rpx;
			display: flex;
			justify-content: center;
			/* 使按钮组居中显示 */
		}

		.button-group {
			display: flex;
			justify-content: space-around;
			width: 100%;
			padding: 20rpx;
		}

		.button-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 20rpx;
			width: 160rpx;
			height: 160rpx;

			.icon-image {
				width: 100rpx;
				height: 100rpx;
				margin-bottom: 20rpx;
				border-radius: 20rpx;
			}

			.button-text {
				font-size: 26rpx;
				line-height: 1;
				color: #333;
			}
		}

		.review-item {
			width: calc(100vw - 48rpx);
			margin: 20rpx 20rpx;
			padding: 40rpx 20px;
			background-color: #FFF;
			border-radius: 32rpx;

			&:first-child {
				margin-top: 0;
			}

			.studyContent {
				margin-top: 20rpx;
				min-height: 70rpx;
			}

			.zexq {
				margin: 12rpx 0;
				max-width: 480rpx;
				font-size: 24rpx;
				font-weight: normal;
				color: #000;

				.item {
					margin-right: 16rpx;
					padding: 2rpx 4rpx;
					border: 1rpx solid #ccc;
				}

				.li_top_info {
					display: flex;
				}

			}

			.sjmc_rank {
				display: flex;
			}

			.rank_name {
				flex: 1;
				paddingLeft: 20rpx;
			}

			.sjmc {
				font-size: 28rpx;
				font-weight: bold;
				white-space: normal;
				word-break: break-all;
				overflow: hidden;

				.rank_level {
					width: 40rpx;
					height: 50rpx;
					line-height: 50rpx;

					img {
						width: 40rpx;
						height: 50rpx;
					}
				}
			}

			.kssj {
				font-size: 28rpx;
				font-weight: normal;
				color: #333;
			}

			.ksfs {
				font-size: 56rpx;

				.success {
					color: #5ac725;
				}

				.warning {
					color: #f9ae3d;
				}

				.error {
					color: #f56c6c;
				}
			}
		}

		.flex-shrink-0 {
			flex-shrink: 0;
		}

		.comment-btn {
			/* 按钮内边距 */
			border: 1px solid #007BFF;
			/* 按钮边框 */
			border-radius: 5px;
			/* 圆角边框 */
			background-color: #FFFFFF;
			/* 按钮背景色 */
			color: #007BFF;
			/* 按钮文字颜色 */
			text-align: center;
			/* 文字居中 */
			cursor: pointer;
			/* 鼠标悬停时显示为手型 */
			transition: background-color 0.3s, color 0.3s;
			/* 添加过渡效果 */
		}

		.comment-btn1 {
			/* 按钮边框 */
			border-radius: 5px;
			/* 圆角边框 */
			color: white;
			/* 按钮文字颜色 */
			text-align: center;
			/* 文字居中 */
			cursor: pointer;
			/* 鼠标悬停时显示为手型 */
			transition: background-color 0.3s, color 0.3s;
			/* 添加过渡效果 */
		}

		.comment-btn:hover {
			background-color: #007BFF;
			color: #FFFFFF;
		}

		.u-flex {
			justify-content: space-between;
		}
	}

	.tab-group {
		display: flex;
		flex-wrap: wrap; // 允许换行
		justify-content: space-around;
		padding: 20rpx 30rpx;
		background-color: #fff;
		border-bottom: 1rpx solid #eee;
	}

	.tab-item {
		flex: 0 0 23%; // 每个标签占据23%的宽度，留出间距
		margin-bottom: 10rpx; // 标签之间的间距
		position: relative;
		padding: 20rpx 0;
		font-size: 30rpx;
		color: #666;
		font-weight: bold;

		&.active {
			color: #4CAF50;
			font-weight: bold;

			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 40rpx;
				height: 4rpx;
				background-color: #4CAF50;
				border-radius: 2rpx;
			}
		}
	}

	.btn-add {
		width: 90rpx;
		height: 90rpx;
		border-radius: 50%;
		position: fixed; // 改为 fixed 定位
		right: 24rpx;
		top: 66.67%;
		transform: translateY(-50%); // 垂直居中调整
		background-color: #FFF;
		border: 2rpx solid #409EFF;
		z-index: 999; // 确保按钮在最上层
	}

	.share-btn {
		position: fixed;
		right: 24rpx;
		top: 80%;
		transform: translateY(-50%);
		background-color: #FFF;
		border: 2rpx solid #409EFF;
		z-index: 999;
		padding: 20rpx;
		border-radius: 50%;
	}

	.subject-tags {
		display: flex;
		justify-content: space-around;
		margin-top: 10rpx; // 添加顶部间距
	}

	.tag {
		padding: 10rpx 20rpx;
		background-color: #f0f0f0;
		border-radius: 15rpx;
		cursor: pointer;
	}

	.tag:hover {
		background-color: #e0e0e0; // 悬停效果
	}
</style>